function playSound() {
  document.getElementById("mysound").play();
  navigator.vibrate(200);
}

function getParams() {
  var url = window.location.href;

  // 获取 URL 参数部分
  var params = url.split("?")[1];

  if (!params) return null;

  // 将参数部分按照 & 分割成数组
  var paramsArray = params.split("&");

  // 创建一个空对象来存储参数
  var paramsObj = {};

  // 遍历参数数组
  paramsArray.forEach(function (param) {
    // 将参数按照 = 分割成键值对
    var keyValue = param.split("=");
    // 将参数存储到对象中
    paramsObj[keyValue[0]] = keyValue[1];
  });
  return paramsObj;
}

function getServerIp() {
  let serverIp = getParams()["server"];
  console.log("server:", serverIp);
  return serverIp;
}
let socket;
let connectd = false;

// 创建 WebSocket 连接
function init() {
  let addr = "ws://192.168.31.79:8080/websocket";
  //let addr = "ws://127.0.0.1:8080/websocket";
  let ip = getServerIp();
  if (ip) {
    addr = "ws://" + ip + ":8080/websocket";
  }
  console.log("server", addr);
  socket = new WebSocket(addr);

  // 监听连接打开事件
  socket.onopen = function (event) {
    console.log("WebSocket connected");
    connectd = true;
    var outputDiv = document.getElementById("link");
    outputDiv.innerHTML = '<font color="#527F76">已连接</font>';
  };

  // 监听接收到消息事件
  socket.onmessage = function (event) {
    var data = event.data;
    console.log("Received data: " + data);
  };

  // 监听连接关闭事件
  socket.onclose = function (event) {
    console.log("WebSocket disconnected");
    connectd = false;
    var outputDiv = document.getElementById("link");
    outputDiv.innerHTML = '<font color="#dc143c">未连接</font>';
  };

  // 监听连接错误事件
  socket.onerror = function (error) {
    console.error("WebSocket error: " + error);
  };
}

// 向服务器发送消息
function sendMessage(s) {
  if (connectd) {
    socket.send(s);
  } else {
    console.error("server not connected");
  }
}

function enter() {
  playSound();
  sendMessage("kb:Enter");
}
function cancel() {
  playSound();
  sendMessage("kb:Escape");
}

function sendKey(key) {
  sendMessage(key);
}

let time = "";
let lock = true;
function down(key) {
  let eventDiv = document.getElementById("event");
  if (eventDiv) {
    eventDiv.innerHTML = "key-down";
  }
  //console.log("keydown");
  time = setInterval(() => {
    // console.log(key);
    if (eventDiv) {
      eventDiv.innerHTML = "send-Message";
    }
    sendMessage(key);
    lock = false;
  }, 200);
}
function up() {
  //console.log("keyup");
  let eventDiv = document.getElementById("event");
  if (eventDiv) {
    eventDiv.innerHTML = "key-up";
  }
  clearTimeout(time);
  //鼠标释放时让lock异步执行，setTimeout因为异步任务，所以会放到任务队列最后执行，让click事件先执行了
  setTimeout(() => {
    lock = true;
  });
}
function cli(key) {
  if (lock) {
    //console.log(key);
    playSound();
    sendMessage(key);
  }
}
